<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams">
      <el-form-item label="样本源编号" prop="sourceCode">
        <el-input
          v-model="queryParams.sourceCode"
          clearable
          placeholder="请输入样本源编号"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="样本源类型" prop="sourceTypeId">
        <treeselect v-model="queryParams.sourceTypeId" :normalizer="normalizer" :options="sourceTypeOptions"
                    placeholder="请选择样本源类型" style="width: 180px"
        />
      </el-form-item>
      <el-form-item label="样本源名称" prop="sourceName">
        <el-input
          v-model="queryParams.sourceName"
          clearable
          placeholder="请输入样本源名称"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="样本源描述" prop="sourceDesc">
        <el-input
          v-model="queryParams.sourceDesc"
          clearable
          placeholder="请输入样本源描述"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="随访状态" prop="followState">
        <el-select
          v-model="queryParams.followState"
          clearable
          placeholder="随访状态"
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in followStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="提醒状态" prop="visitReminder">
        <el-select
          v-model="queryParams.visitReminder"
          clearable
          placeholder="提醒状态"
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in reminderOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:source:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['research:follow:edit']"
          :disabled="single"
          icon="el-icon-plus"
          plain
          size="mini"
          type="info"
          @click="handleFollow"
        >随访
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:source:edit']"
          :disabled="single"
          icon="el-icon-edit"
          plain
          size="mini"
          type="success"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:source:remove']"
          :disabled="multiple"
          icon="el-icon-delete"
          plain
          size="mini"
          type="danger"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:source:import']"
          icon="el-icon-upload2"
          plain
          size="mini"
          type="info"
          v-show="powerVisible"
          @click="handleImport"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:source:export']"
          icon="el-icon-download"
          plain
          size="mini"
          type="warning"
          v-show="powerVisible"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
     <el-col :span="1.5">
       <!-- <el-button
         v-hasPermi="['biobank:source:add']"
         icon="el-icon-plus"
         plain
         size="mini"
         type="primary"
         @click="handlePatient"
       >用药信息查询
       </el-button> -->
     </el-col>
      <el-col :span="1.5">

        <el-button
          v-hasPermi="['biobank:source:query']"
          :disabled="ids.length == 0"
          icon="el-icon-plus"
          plain
          size="mini"
          type="danger"
          @click="handleAlarm"
        >提醒患者
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['biobank:source:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          v-show="powerVisible"
          @click="handleAlreadyAlarm"
        >已提醒患者
        </el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sourceList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column v-if="false" align="center" label="样本源ID" prop="sourceId"/>
      <el-table-column align="center" label="身份证号" prop="idCard"/>
      <el-table-column align="center" label="样本源编号" prop="sourceCode"/>
      <el-table-column align="center" label="样本源类型" prop="sourceTypeName"/>
      <el-table-column align="center" label="样本源名称" prop="sourceName"/>
      <el-table-column :show-overflow-tooltip="true" align="center" label="样本源描述" prop="sourceDesc"/>
      <el-table-column :formatter="statusFormat" align="center" label="随访状态" prop="followState"/>
      <el-table-column align="center" label="提醒状态" prop="visitReminder">
        <template slot-scope="scope">
          <span v-if="scope.row.visitReminder == '1'">已提醒</span>
          <span v-else>未提醒</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="自定义表单key" prop="formKey"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-link"
            size="mini"
            type="text"
            @click="relateSample(scope.row)"
          >关联样本
          </el-button>
          <el-button
            v-hasPermi="['biobank:source:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
<!--          <el-button-->
<!--            v-hasPermi="['biobank:source:edit']"-->
<!--            icon="el-icon-edit"-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            @click="handleAlarm(scope.row)"-->
<!--          >提醒-->
<!--          </el-button>-->
          <el-button
            v-hasPermi="['biobank:source:remove']"
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
          <el-button
            v-hasPermi="['biobank:source:add']"
            icon=""
            size="mini"
            type="text"
            v-show="powerVisible"
            @click="handleYYDetail(scope.row)"
          >用药详情
          </el-button>
          <el-button
            v-hasPermi="['biobank:source:add']"
            icon=""
            size="mini"
            type="text"
            v-show="powerVisible"
            @click="handleZDDetail(scope.row)"
          >诊断信息
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改样本源 对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="700px">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="样本源编号" prop="sourceCode">
              <el-input v-model="form.sourceCode" placeholder="请输入样本源编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="样本源名称" prop="sourceName">
              <el-input v-model="form.sourceName" placeholder="请输入样本源名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="身份证号" prop="idCard" >
              <el-input v-model="form.idCard" placeholder="身份证号" @blur="getPatientInfo"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="样本源类型" prop="sourceTypeId">
              <treeselect v-model="form.sourceTypeId" :normalizer="normalizer" :options="sourceTypeOptions"
                          placeholder="请选择样本源类型"
                          @select="sourceTypeSelect"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="随访状态" prop="followState">
              <el-select
                v-model="form.followState"
                clearable
                placeholder="随访状态"
                size="small"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in followStateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="自定义表单key" prop="formKey">
          <el-input v-model="form.formKey" disabled placeholder="请输入自定义表单key"/>
        </el-form-item>
        <el-form-item label="样本源描述" prop="sourceDesc">
          <el-input v-model="form.sourceDesc" :rows="2" placeholder="请输入样本源描述" type="textarea"/>
        </el-form-item>
      </el-form>
      <file-upload :value="form.attaches" style="margin-top: 16px" @fileEvent="fileUploadEvent"></file-upload>
      <el-divider><i class="el-icon-s-promotion"></i></el-divider>
      <div
        v-for="(domain, index) in form.formJson"
        :key="index"
        :label="domain.controlLable"
      >
        <parser ref="formCustom" :form-conf="domain.json"/>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加随访 -->
    <el-dialog :visible.sync="addOpen" append-to-body title="添加随访" width="700px">
      <el-form ref="followForm" :model="followForm" :rules="addRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="样本源名称" prop="sourceId">
              <el-input v-model="followForm.sourceName" :disabled="true" placeholder="样本源名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="问卷表单" prop="formKey">
              <el-select
                v-model="followForm.formKey"
                clearable
                placeholder="问卷表单"
                size="small"
                style="width: 214px"
              >
                <el-option
                  v-for="dict in customForms"
                  :key="dict.formKey"
                  :label="dict.formName"
                  :value="dict.formKey"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="随访状态" prop="followState">
              <el-select
                v-model="followForm.followState"
                clearable
                placeholder="随访状态"
                size="small"
                style="width: 214px"
              >
                <el-option
                  v-for="dict in followStateOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="随访方式" prop="followWay">
              <el-select
                v-model="followForm.followWay"
                clearable
                placeholder="随访状态"
                size="small"
                style="width: 214px"
              >
                <el-option
                  v-for="dict in followWayOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="参与随访人员">
          <el-tag
            v-for="visitor in visitors"
            :key="visitor"
            :disable-transitions="false"
            @close="handleVisitorClose(visitor)"
          >
            {{ visitor }}
          </el-tag>
          <el-input
            v-if="visitorVisible"
            ref="saveVisitorInput"
            v-model="visitorValue"
            class="input-new-tag"
            size="small"
            @blur="handleVisitorConfirm"
            @keyup.enter.native="handleVisitorConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showVisitor">+ 随访人员</el-button>
        </el-form-item>
        <el-form-item label="随访描述" prop="followDesc">
          <el-input v-model="followForm.followDesc" :rows="2" placeholder="请输入随访描述" type="textarea"/>
        </el-form-item>
        <el-form-item label="随访方案">
          <el-tabs :active-name="activeTab">
            <el-tab-pane label="单次随访" name="one">
              <el-form-item label="计划随访时间" prop="followPlan">
                <el-date-picker v-model="form.followPlan" clearable
                                placeholder="选择计划随访时间"
                                size="small"
                                style="width: 300px"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="模板随访" name="temp">
              <el-form-item label="首次随访时间" prop="followPlan">
                <el-date-picker v-model="form.followPlan" clearable
                                placeholder="选择计划随访时间"
                                size="small"
                                style="width: 300px"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="随访模板" prop="followTempId">
                <el-select
                  v-model="form.followTempId"
                  clearable
                  placeholder="随访模板"
                  size="small"
                  style="width: 300px"
                >
                  <el-option
                    v-for="dict in followTempList"
                    :key="dict.followTempId"
                    :label="dict.followTempName"
                    :value="dict.followTempId"
                  />
                </el-select>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="规律性随访" name="law">
              <el-form-item label="首次随访时间" prop="followPlan">
                <el-date-picker v-model="form.followPlan" clearable
                                placeholder="选择计划随访时间"
                                size="small"
                                style="width: 300px"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="间隔时间" prop="intervalTime">
                <el-input-number v-model="followForm.intervalTime" controls-position="right" style="width: 100px"
                ></el-input-number>
                <el-select v-model="followForm.intervalUnit" placeholder="请选择时间单位" style="width: 200px">
                  <el-option
                    v-for="item in timeType"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="随访次数" prop="followCount" style="margin-top: 10px">
                <el-input-number v-model="followForm.followCount" controls-position="right" style="width: 300px"
                ></el-input-number>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFollowForm">确 定</el-button>
        <el-button @click="cancelFollow">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 关联样本 对话框 -->
    <el-dialog :visible.sync="relateOpen" append-to-body title="关联样本" width="90%">
      <el-table ref="table" v-loading="relateLoading" :data="sampleList" height="600" size="small">
        <el-table-column align="center" label="样本复份编号" prop="sampBackupCode"/>
        <el-table-column align="center" label="样本类型" prop="sampTypeName"/>
        <el-table-column align="center" label="样本源名称" prop="sampSourceName"/>
        <el-table-column align="center" label="采样时间" prop="samplingTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.samplingTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="样本位置" prop="sampLocation" width="300"/>
        <el-table-column align="center" label="样本源类型" prop="sampSourceTypeName"/>
        <el-table-column align="center" label="样本组" prop="sampGroupName"/>
        <el-table-column align="center" label="样本量" prop="sampQuantity"/>
        <el-table-column align="center" label="样本单位" prop="sampUnit"/>
        <el-table-column :formatter="sampStateFormat" align="center" label="样本状态" prop="sampState"/>
        <el-table-column align="center" label="冻融次数" prop="sampFreezeThawCount"/>
        <el-table-column align="center" label="条码/二维码" prop="qrCode"/>
      </el-table>
      <pagination
        v-show="relateTotal>0"
        :limit.sync="relateParams.pageSize"
        :page.sync="relateParams.pageNum"
        :total="relateTotal"
        @pagination="getRelateSamples"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelRelate">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 样本源导入 对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" append-to-body width="400px">
      <el-upload
        ref="upload"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :auto-upload="false"
        :disabled="upload.isUploading"
        :headers="upload.headers"
        :limit="1"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        accept=".xlsx, .xls"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          <el-checkbox v-model="upload.updateSupport"/>
          是否更新已经存在的样本源
          <el-link style="font-size:12px" type="info" @click="importTemplate">下载模板</el-link>
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <patient-dialog :patientVisible.sync="patientVisible"></patient-dialog>
    <patientYYDetailDialog :patientYYDetailVisible.sync="patientYYDetailVisible" :idCard="this.idCard"></patientYYDetailDialog>
    <patientZDDetailDialog :patientZDDetailVisible.sync="patientZDDetailVisible" :idCard="this.idCard"></patientZDDetailDialog>
<!--    <already-alarm-dialog :patientAlreadyVisible.sync="patientAlreadyVisible" @getList="getList"></already-alarm-dialog>-->
  </div>
</template>

<script>
import {
  addSource,
  delSource,
  exportSource,
  getImportTemplate,
  getSource,
  listSource,
  updateSource
} from '@/api/biobank/source'
import { allForm, formJsonShow } from '@/api/tool/form'
import { listSourceType } from '@/api/biobank/sourceType'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import Parser from 'form-gen-parser'
import FileUpload from '@/components/FileUpload'
import { addFollow } from '@/api/research/follow'
import { listFollowTemp } from '@/api/research/followTemp'
import { getPatientInfo, listSample, setUpPatientReminders } from '@/api/biobank/sample'
import { getToken } from '@/utils/auth'
import patientDialog from './module/patientDialog'
import patientYYDetailDialog from './module/patientYYDetailDialog.vue'
import patientZDDetailDialog from './module/patientZDDetailDialog.vue'
// import alreadyAlarmDialog from "./module/alreadyAlarmDialog";

export default {
  name: 'SourceList',
  components: {
    Treeselect,
    Parser,
    FileUpload,
    patientDialog,
    patientYYDetailDialog,
    patientZDDetailDialog,
    // alreadyAlarmDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 关联样本 遮罩层
      relateLoading: false,
      // 选中数组
      ids: [],
      // 选中数组
      selectSource: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 关联样本 总条数
      relateTotal: 0,
      // 样本源 表格数据
      sourceList: [],
      // 关联样本 表格数据
      sampleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 添加随访弹出层
      addOpen: false,
      // 关联样本弹出层
      relateOpen: false,
      // 添加随访人员 input visible
      visitorVisible: false,
      // 添加随访人员 input value
      visitorValue: '',
      // 随访方案
      activeTab: 'one',
      // 随访人员数组
      visitors: [],
      // 随访状态
      followStateOptions: [],
      // 随访方式
      followWayOptions: [],

      //提醒状态
      reminderOptions: [
        {
          label: "全部",
          value: ""
        },
        {
          label: "已提醒",
          value: "1"
        },
        {
          label: "未提醒",
          value: "0"
        }
      ],
      // 问卷表单
      customForms: [],
      // 随访模板
      followTempList: [],
      // 样本状态
      sampStateOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'createTime',
        isAsc: 'DESC',
        sourceCode: undefined,
        sourceTypeId: undefined,
        sourceName: undefined,
        sourceDesc: undefined,
        followState: undefined,
        visitReminder: "",
        idCard: undefined
      },
      // 关联样本查询参数
      relateParams: {
        pageNum: 1,
        pageSize: 20,
        sampSourceId: undefined
      },
      // 样本源类型 树选项
      sourceTypeOptions: [],
      // 时间单位
      timeType: [
        { key: 'h', value: '时' },
        { key: 'd', value: '天' },
        { key: 'w', value: '周' },
        { key: 'm', value: '月' },
        { key: 'y', value: '年' }
      ],
      // 样本源数据导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的样本源
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/biobank/source/importData'
      },
      // 表单参数
      form: {},
      // 随访表单参数
      followForm: {},
      // 表单校验
      rules: {
        sourceCode: [{ required: true, trigger: 'blur', message: '样本源编号不能为空' }, {
          max: 50,
          trigger: 'blur',
          message: '样本源编号不能超过50个字符'
        }],
        sourceTypeId: { required: true, trigger: 'blur', message: '样本源类型不能为空' },
        sourceName: [{ required: true, trigger: 'blur', message: '样本源名称不能为空' }, {
          max: 50,
          trigger: 'blur',
          message: '样本源名称不能超过50个字符'
        }],
        sourceDesc: { max: 50, trigger: 'blur', message: '样本源描述不能超过100个字符' },
        idCard:[{ required: true, trigger: 'blur', message: '身份证号不能为空' },{max:18,min:18,trigger:'blur',message:'输入正确的18位身份证号'}]
      },
      // 添加随访表单校验
      addRules: {
        followState: { required: true, trigger: 'change', message: '随访状态不能为空' },
        followWay: { required: true, trigger: 'change', message: '随访方式不能为空' }
      },

      //用药信息
      patientVisible: false,
      patientYYDetailVisible:false,
      patientZDDetailVisible:false,
      idCard:'',

      //已提醒患者
      patientAlreadyVisible: false,

      //用药按钮是否显示
      powerVisible: true,

    }
  },
  created() {
    this.getList()
    this.getTreeselect()
    this.getDicts('follow_state').then(response => {
      this.followStateOptions = response.data
    })
    this.getDicts('follow_way_type').then(response => {
      this.followWayOptions = response.data
    })
    this.getDicts('sample_state').then(response => {
      this.sampStateOptions = response.data
    })
    this.getCustomForm()
    this.getFollowTemp()
    let rolePower = this.$store.getters.roles;
    if(rolePower[0] == "admin"){
      this.powerVisible = true;
    }else{
      this.powerVisible = false;
    }
  },
  methods: {
    // 关联样本按钮点击事件
    relateSample(row) {
      this.relateOpen = true
      this.relateParams.pageNum = 1
      this.relateParams.sampSourceId = row.sourceId
      this.getRelateSamples()
    },
    // 关联样本对话框取消按钮点击事件
    cancelRelate() {
      this.relateOpen = false
    },
    // 获取关联样本
    getRelateSamples() {
      this.relateLoading = true
      listSample(this.relateParams).then(response => {
        this.sampleList = response.rows
        this.relateTotal = response.total
        this.relateLoading = false
      })
    },
    // 附件上传子组件回调
    fileUploadEvent(fileList) {
      this.form.attaches = fileList
    },
    /** 查询样本源 列表 */
    getList() {
      this.loading = true
      listSource(this.queryParams).then(response => {
        this.sourceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 样本源类型下拉框选择事件
    sourceTypeSelect(node, instanceId) {
      this.form.formKey = node.formKey
      this.showFormJson(node.formKey)
    },
    // 菜单状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.followStateOptions, row.followState)
    },
    // 渲染动态表单
    showFormJson(formKey) {
      if (!formKey || formKey === '') {
        this.$set(this.form, 'formJson', undefined)
        return false
      }
      formJsonShow(formKey).then(response => {
        let formJson = []
        for (let oncekey in response.data) {
          let datas = response.data[oncekey]
          if (datas) {
            for (let i = 0; i < datas.length; i++) {
              let once = datas[i]
              if (/^{/.test(once)) {
                formJson.push({
                  json: JSON.parse(once)
                })
              }
            }
          }
        }
        this.$set(this.form, 'formJson', formJson)
        if (this.form.formData != undefined) {
          this.fillFormData(this.form.formJson[0].json, JSON.parse(this.form.formData))
          this.$set(this.form, 'formJson', formJson)
        }
      })
    },
    // 动态表单值回写
    fillFormData(form, data) {
      form.fields.map(item => {
        if (item.__vModel__) {
          const val = data[item.__vModel__]
          if (val) {
            item.__config__.defaultValue = val
          }
          return item
        } else {
          if (item.__config__ && item.__config__.children && item.__config__.children.length > 0) {
            item.__config__.children.forEach(child => {
              const childVal = data[child.__vModel__]
              if (childVal) {
                child.__config__.defaultValue = childVal
              }
            })
            return item
          }
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        sourceId: undefined,
        sourceCode: undefined,
        sourceTypeId: undefined,
        sourceName: undefined,
        sourceDesc: undefined,
        attaches: undefined,
        followState: undefined,
        visitReminder: "",
        formKey: undefined,
        formDesc: undefined,
        formData: undefined,
        formJson: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        idCard: undefined
      }
      this.resetForm('form')
    },
    resetFollow() {
      this.followForm = {
        followId: undefined,
        sourceId: undefined,
        followPlan: undefined,
        followFact: undefined,
        followNum: undefined,
        followVisitor: undefined,
        followDesc: undefined,
        followState: undefined,
        followWay: undefined,
        formKey: undefined,
        formData: undefined,
        formDesc: undefined,
        followTempId: undefined,
        intervalTime: undefined,
        intervalUnit: undefined,
        followCount: undefined
      }
      this.resetForm('followForm')
    },
    /** 转换样本源类型 数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.sourceTypeId,
        label: node.sourceTypeName,
        children: node.children
      }
    },
    /** 查询样本源类型下拉树结构 */
    getTreeselect() {
      listSourceType().then(response => {
        this.sourceTypeOptions = this.handleTree(response.data, 'sourceTypeId', 'parentId')
      })
    },
    /** 样本状态状态字典翻译 */
    sampStateFormat(row, column) {
      return this.selectDictLabel(this.sampStateOptions, row.sampState)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sourceId)
      this.selectSource = selection
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加样本源 '
    },
    // 添加到随访
    handleFollow() {
      this.resetFollow()
      this.addOpen = true
      this.followForm.sourceName = this.selectSource[0].sourceName
      this.followForm.sourceId = this.selectSource[0].sourceId
    },
    // -- 添加随访人员 -- start
    handleVisitorClose(visitor) {
      this.visitors.splice(this.visitors.indexOf(visitor), 1)
    },
    showVisitor() {
      this.visitorVisible = true
      this.$nextTick(_ => {
        this.$refs.saveVisitorInput.$refs.input.focus()
      })
    },
    handleVisitorConfirm() {
      let inputValue = this.visitorValue
      if (inputValue) {
        this.visitors.push(inputValue)
      }
      this.visitorVisible = false
      this.visitorValue = ''
    },
    // -- 添加随访人员 -- end
    // 获取所有问卷表单
    getCustomForm() {
      let queryForm = {}
      queryForm.formType = 'question'
      allForm(queryForm).then(response => {
        this.customForms = response.data
      })
    },
    // 获取随访模板
    getFollowTemp() {
      listFollowTemp().then(response => {
        this.followTempList = response.data
      })
    },
    /** 提交按钮 */
    submitFollowForm() {
      this.followForm.followVisitor = this.visitors.join(',')
      this.$refs['followForm'].validate(valid => {
        if (valid) {
          addFollow(this.followForm).then(response => {
            this.msgSuccess('添加到随访成功')
            this.addOpen = false
          })
        }
      })
    },
    cancelFollow() {
      this.addOpen = false
      this.resetFollow()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const sourceId = row.sourceId || this.ids
      getSource(sourceId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改样本源 '
        this.showFormJson(row.formKey)
      })
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.formJson) {
        let custFormRef = this.$refs.formCustom[0]
        let custForm = custFormRef.$refs[custFormRef.formConf.formRef]
        let custData = custFormRef[custFormRef.formConf.formModel]
        let custDesc = {}
        for (let onceForm of this.form.formJson) {
          for (let onceField of onceForm.json.fields) {
            if (onceField.__vModel__) {
              custDesc[onceField.__vModel__] = onceField.__config__.label
            } else {
              if (onceField.__config__ && onceField.__config__.children && onceField.__config__.children.length > 0) {
                onceField.__config__.children.forEach(child => {
                  custDesc[child.__vModel__] = child.__config__.label
                })
              }
            }
          }
        }
        let formDataDto = { data: custData, desc: custDesc }
        // 自定义表单的核验
        custForm.validate(e => {
          if (e) {
            this.form.formDataSaveDto = formDataDto
          }
        })
      }

      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.sourceId != null) {
            updateSource(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addSource(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sourceIds = row.sourceId || this.ids
      this.$confirm('是否确认删除所选的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delSource(sourceIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },

    handleYYDetail(row){
      console.log(row)
      this.idCard = row.idCard
      this.patientYYDetailVisible = !this.patientYYDetailDialog

    },
    handleZDDetail(row){
      this.idCard = row.idCard
      this.patientZDDetailVisible = !this.patientZDDetailVisible
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '样本信息导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      getImportTemplate().then(response => {
        this.download(response.msg)
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有样本源 数据项?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(function() {
        return exportSource(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    },

    // /**
    //  * @description: 打开用药信息
    //  * @return {*}
    //  */
    handlePatient() {
      this.patientVisible = !this.patientVisible
    },

    /**
     * @description: 提醒患者
     * @return {*}
     */
    handleAlarm(row) {
      // console.log(row)
      let list = []
      if (row) {
        // list.push(row.sourceId)
        list.push(...this.ids)
      } else {
        list = this.ids
      }
      let params = {
        ids: list
      }
      setUpPatientReminders(params).then(response => {
        if (response.code == 200) {
          this.msgSuccess('批量提醒成功')
        }
      })
    },

    handleAlreadyAlarm(){
      this.patientAlreadyVisible = !this.patientAlreadyVisible;
    },

    getPatientInfo() {
      getPatientInfo(this.form.idCard).then(response => {
        this.form.sourceName = response.data.patientName
      })
    }
  }
}
</script>
<style scoped>
.el-tag + .el-tag {
  margin-left: 7px;
}

.button-new-tag {
  margin-left: 7px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 7px;
  vertical-align: bottom;
}
</style>
